//
//  YCToast.m
//  Toast
//
//  Created by 唐可雄 on 2018/3/26.
//  Copyright © 2018年 yc. All rights reserved.
//

#import "YCToast.h"

static YCToast *toast;

@interface YCToast ()

@property (nonatomic, strong) UILabel *textLabel;

@end

@implementation YCToast

+ (void)show:(NSString *)str {
    if (!toast) {
        toast = [[YCToast alloc] init];
        [toast initLabel:str];
        [toast initSelf];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [toast removeFromSuperview];
            toast = nil;
        });
    } else {
        [toast removeFromSuperview];
        toast = nil;
        [self show:str];
    }
}

- (void)initLabel:(NSString *)str {
    CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    UIFont *font = [UIFont systemFontOfSize:15];
    CGFloat width = screenWidth / 3.0 * 2.0;
    CGSize labelSize = [self caculateTextNeedSize:str andFont:font andWith:width];
    self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, labelSize.width, labelSize.height)];
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.textLabel.textColor = [UIColor whiteColor];
    self.textLabel.font = font;
    self.textLabel.text = str;
    self.textLabel.numberOfLines = 0;
    self.textLabel.textAlignment = NSTextAlignmentCenter;
}

- (void)initSelf {
    CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    self.backgroundColor = [UIColor colorWithRed:10.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:0.8];
    self.frame = CGRectMake((screenWidth - self.textLabel.frame.size.width)/2.0, screenHeight/3.0 * 2.0 + screenHeight/3.0/2.0, self.textLabel.frame.size.width + 20, self.textLabel.frame.size.height + 20);
    [self addSubview:self.textLabel];
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 10;
    UIWindow *window = [self getCurrentWindow];
    [window addSubview:self];
    [window bringSubviewToFront:self];
}

- (UIWindow *)getCurrentWindow {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    return window;
}

- (CGSize)caculateTextNeedSize:(NSString *)str andFont:(UIFont *)font andWith:(CGFloat)width {
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:font}];
    CGSize labelSize = [attrStr boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    return labelSize;
}

@end
